package org.libermundi.theorcs.security.dao.hibernate;

import java.util.Date;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.criterion.Restrictions;
import org.libermundi.theorcs.core.dao.hibernate.HibernateGenericDao;
import org.libermundi.theorcs.security.dao.RememberMeTokenDao;
import org.libermundi.theorcs.security.model.RememberMeToken;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.web.authentication.rememberme.PersistentRememberMeToken;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Repository(value="rememberMeTokenDao")
@Transactional(rollbackFor = Exception.class, propagation=Propagation.REQUIRED)
public class RememberMeTokenDaoImpl extends HibernateGenericDao<RememberMeToken, Long> implements RememberMeTokenDao {
	private static final Logger logger = LoggerFactory.getLogger(RememberMeTokenDaoImpl.class); 
	
	public RememberMeTokenDaoImpl(){
		super();
		_mappedClazz = RememberMeToken.class;
	}	

	@Override
	public void createNewToken(PersistentRememberMeToken token) {
		RememberMeToken tokenToSave = transform(token);
		if(logger.isDebugEnabled()) {
			logger.debug("Saving RememberMeToken : " + tokenToSave);
		}
		save(tokenToSave);
	}

	@Override
	public void updateToken(String series, String tokenValue, Date lastUsed) {
		RememberMeToken token = getTokenbySeries(series);
		token.setDate(lastUsed);
		token.setTokenValue(tokenValue);
		save(token);
	}

	@Override
	public PersistentRememberMeToken getTokenForSeries(String seriesId) {
		return transform(getTokenbySeries(seriesId)); 
	}

	@Override
	@SuppressWarnings("unchecked")
	public void removeUserTokens(String username) {
		List<RememberMeToken> listToDelete = createSimpleCriteria().add(Restrictions.eq(RememberMeToken.PROP_USERNAME, username)).list();
		delete(listToDelete.toArray(new RememberMeToken[listToDelete.size()]));
	}
	
	@Override
	public RememberMeToken getTokenbySeries(String seriesId) {
		Criteria criteria = createSimpleCriteria();
		criteria.add(Restrictions.eq(RememberMeToken.PROP_SERIES, seriesId));
		return (RememberMeToken)criteria.uniqueResult();
	}	
	
	private static PersistentRememberMeToken transform(RememberMeToken token){
		if(token != null) {
			return new PersistentRememberMeToken(token.getUsername(), token.getSeries(), token.getTokenValue(), token.getDate());
		}
		return null;
	}

	private static RememberMeToken transform(PersistentRememberMeToken token){
		return new RememberMeToken(token.getUsername(), token.getSeries(), token.getTokenValue(), token.getDate());
	}



}
